package com.itheima.web.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import com.itheima.domain.db.Admin;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import com.itheima.web.manager.AdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

    @Autowired
    private AdminManager adminManager;

    @GetMapping("/system/users/verification")
    public void sendCode(String uuid, HttpServletResponse response) throws IOException {
        //生成验证码
        LineCaptcha lineCaptcha = adminManager.sendCode(uuid);
        //传输给浏览器
        lineCaptcha.write(response.getOutputStream());
    }

    /**
     * 登录
     * @param map 参数(用户名,密码,验证码,uuid)
     * @return token
     */
    @PostMapping("/system/users/login")
    public Map login(@RequestBody Map<String,String> map) throws BusinessException {
        String username = map.get("username");
        String password = map.get("password");
        String verificationCode = map.get("verificationCode");
        String uuid = map.get("uuid");
        String token = adminManager.login(username, password, verificationCode, uuid);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return tokenMap;
    }

    /**
     * 查询用户个人信息
     * @param token token
     * @return 个人信息
     */
    @PostMapping("/system/users/profile")
    public Admin findAdminInfo(@RequestHeader("Authorization") String token) {
        //解析token
        //前端拿到token后自动的在前面拼接一个前缀  Bearer
        //去掉前端自动携带的前缀
        token = token.replace("Bearer " , "");
        //解析token
        Map map = JwtUtil.parseToken(token);
        //
        Admin admin = BeanUtil.mapToBean(map, Admin.class, true);
        //查询用户的个人信息
        return adminManager.findAdminInfo(admin);
    }

    /**
     * 用户登出
     * @param token 令牌
     */
    @PostMapping("/system/users/logout")
    public Admin logout(@RequestHeader("Authorization") String token) {
        //解析token
        //前端拿到token后自动的在前面拼接一个前缀  Bearer
        //去掉前端自动携带的前缀
        token = token.replace("Bearer " , "");
        return adminManager.logout(token);
    }
    //动态人工拒绝
    @PostMapping("/manage/messages/reject")
    public Map rejectMovement(@RequestBody String[] movementIds){
        return adminManager.rejectMovement(movementIds);
    }
    //动态人工通过
    @PostMapping("/manage/messages/pass")
    public Map passMovement(@RequestBody String[] movementIds){
        return adminManager.passMovement(movementIds);
    }

}
